﻿//------------------------------------------------------------------------------
// ╭─────────────────────────────╮
// │ ╭─╮     ╭─╮              TM │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// │ │ │     │ │                 │                                           ☺  
// │ │ ╰───╮ │ │ ╭─────╮ ╭─────╮ │     Name:Wedn.Net 前台页面控制器        ♮ ♪ ♩
// │ │ ╭─╮ │ │ │ │ ╭─╮ │ │ ╭─╮ │ │                                    ♫ ♭      
// │ │ ╰─╯ │ │ │ │ ╰─╯ │ │ ╰─╯ │ │     Author:iceStone               ♬ ♪       
// │ └─────╯ └─╯ ╰─────╯ ╰───╮ │ │     Chinese:汪磊                              
// │                     ┌───╯ │ │                                              
// │                     ╰─────╯ │   ╠═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╬═╣
// ╰─────────────────────────────╯                                              
//------------------------------------------------------------------------------
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.UI;
using Wedn.Net.Common;
using Wedn.Net.Controller.Base;
using Wedn.Net.Extensions;
using Wedn.Net.Model;
using Wedn.Net.TEngine;
using Wedn.Net.Utility;

namespace Wedn.Net.Controller
{
    /// <summary>
    /// 前台页面控制器
    /// </summary>
    public class BlogController : FrontBaseController
    {
        #region 首页 +ViewResult Index(string q, int page = 1)
        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="q">搜索关键词</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        [OutputCache(Duration = 300, VaryByParam = "none", VaryByCustom = "ThemeVersion", Location = OutputCacheLocation.Server)]
        public ViewResult Index(string q, int page = 1)
        {
            if (!string.IsNullOrEmpty(q)) return Search(q, page);
            int totalCount;
            var posts = BllInstance.PostManager.SelectPage(page, Setting.PageSize, out totalCount, p => p.Status == (int)PostStatus.Default && p.Type == (int)PostType.Article, p => p.PubDate, true);
            var users = BllInstance.UserManager.Select(u => true).ToList();
            var terms = BllInstance.TermManager.Select(t => true).ToList();
            var relations = BllInstance.RelationManager.Select(r => r.ObjectType == (short)RelationObjectType.Post).ToList();
            foreach (var item in posts)
            {
                var rIds = relations.Where(r => r.ObjectId == item.Id).Select(r => r.TermId).ToArray();
                var itemTerms = terms.Where(t => rIds.Contains(t.Id)).ToList();
                item.Link = Url.Post(item.Slug);
                var user = users.FirstOrDefault(u => u.Id == item.UserId);
                if (user != null)
                    item.Author = user;
                item.Categorys = itemTerms.Where(c => c.Type == (short)TermType.PostCategory);
                item.Tags = itemTerms.Where(c => c.Type == (short)TermType.PostTag);
            }
            ViewBag.Posts = posts;
            ViewBag.CurrentPage = page;
            ViewBag.TotalCount = totalCount;

            ViewBag.Title = string.Format("{0} | {1} - Powered by {2}", Setting.SiteName, Setting.SiteDescription, Setting.Generator);

            return View(TemplateConfig.IndexViewName);
        }
        #endregion

        #region 分类列表页 +ViewResult Category(string item, int page = 1)
        /// <summary>
        /// 分类列表页
        /// </summary>
        /// <param name="item">分类项</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        public ViewResult Category(string item, int page = 1)
        {
            var terms = BllInstance.TermManager.Select(t => true).ToList();
            var relations = BllInstance.RelationManager.Select(r => r.ObjectType == (short)RelationObjectType.Post).ToList();
            var currentCategory = terms.FirstOrDefault(t => t.Slug == item || t.Name == item);
            if (currentCategory == null) { ShowNotFoundPage(); return null; }
            var currentRelIds = relations.Where(r => r.TermId == currentCategory.Id).Select(r => r.ObjectId);

            int totalCount;
            var posts = BllInstance.PostManager.SelectPage(page, Setting.PageSize, out totalCount, p => p.Status == (int)PostStatus.Default && p.Type == (int)PostType.Article && currentRelIds.Contains(p.Id), p => p.PubDate, true);
            var users = BllInstance.UserManager.Select(u => true).ToList();
            foreach (var post in posts)
            {
                var rIds = relations.Where(r => r.ObjectId == post.Id).Select(r => r.TermId).ToArray();
                var itemTerms = terms.Where(t => rIds.Contains(t.Id)).ToList();
                post.Link = Url.Post(post.Slug);
                var user = users.FirstOrDefault(u => u.Id == post.UserId);
                if (user != null)
                {
                    user.Link = Url.Author(user.Login);
                    post.Author = user;
                }
                post.Categorys = itemTerms.Where(c => c.Type == (short)TermType.PostCategory);
                post.Tags = itemTerms.Where(c => c.Type == (short)TermType.PostTag);
            }
            ViewBag.Posts = posts;
            ViewBag.ListItem = new MvcHtmlString(string.Format("分类“<a href=\"{0}\">{1}</a>”下的内容", Url.Action("Category", "Blog", new { item }), currentCategory.Name));
            ViewBag.ListDescription = currentCategory.Description;
            ViewBag.CurrentPage = page;
            ViewBag.TotalCount = totalCount;
            ViewBag.Title = string.Format("分类“{0}”下的文章 - 第{1}页 | {2} - Powered by {3}", currentCategory.Name, page, Setting.SiteName, Setting.Generator);
            return View(TemplateConfig.ListViewName);
        }
        #endregion

        #region 标签列表页 +ViewResult Tag(string item, int page = 1)
        /// <summary>
        /// 标签列表页
        /// </summary>
        /// <param name="item">标签项</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        public ViewResult Tag(string item, int page = 1)
        {
            var terms = BllInstance.TermManager.Select(t => true).ToList();
            var relations = BllInstance.RelationManager.Select(r => r.ObjectType == (short)RelationObjectType.Post).ToList();
            var currentTag = terms.FirstOrDefault(t => t.Name == item);
            if (currentTag == null) { ShowNotFoundPage(); return null; }
            var currentRelIds = relations.Where(r => r.TermId == currentTag.Id).Select(r => r.ObjectId);

            int totalCount;
            var posts = BllInstance.PostManager.SelectPage(page, Setting.PageSize, out totalCount, p => p.Status == (int)PostStatus.Default && p.Type == (int)PostType.Article && currentRelIds.Contains(p.Id), p => p.PubDate, true);
            var users = BllInstance.UserManager.Select(u => true).ToList();
            foreach (var post in posts)
            {
                var rIds = relations.Where(r => r.ObjectId == post.Id).Select(r => r.TermId).ToArray();
                var itemTerms = terms.Where(t => rIds.Contains(t.Id)).ToList();
                post.Link = Url.Post(post.Slug);
                var user = users.FirstOrDefault(u => u.Id == post.UserId);
                if (user != null)
                {
                    user.Link = Url.Author(user.Login);
                    post.Author = user;
                }
                post.Categorys = itemTerms.Where(c => c.Type == (short)TermType.PostCategory);// string.Join("、",.Select(c => string.Format("<a href=\"{0}\" target=\"_blank\" class=\"label label-important\">{1}<i class=\"label-arrow\"></i></a>", Url.Action("Category", "Blog", new { item = !string.IsNullOrEmpty(c.Slug) ? c.Slug : c.Name }), c.Name)));
                post.Tags = itemTerms.Where(c => c.Type == (short)TermType.PostTag);//string.Join("、", .Select(c => string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", Url.Action("Tag", "Blog", new { item = !string.IsNullOrEmpty(c.Slug) ? c.Slug : c.Name }), c.Name)));
            }
            ViewBag.Posts = posts;
            ViewBag.ListItem = new MvcHtmlString(string.Format("打上标签“<a href=\"{0}\">{1}</a>”的内容", Url.Action("Tag", "Blog", new { item }), currentTag.Name));
            ViewBag.ListDescription = currentTag.Description;
            ViewBag.CurrentPage = page;
            ViewBag.TotalCount = totalCount;

            ViewBag.Title = string.Format("标签“{0}”下的文章 - 第{1}页 | {2} - Powered by {3}", currentTag.Name, page, Setting.SiteName, Setting.Generator);
            return View(TemplateConfig.ListViewName);
        }
        #endregion

        #region 作者列表页 +ViewResult Author(string item, int page = 1)
        /// <summary>
        /// 作者列表页
        /// </summary>
        /// <param name="item">作者项</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        public ViewResult Author(string item, int page = 1)
        {
            var author = BllInstance.UserManager.SelectSingle(u => u.Login == item);
            if (author == null) { ShowNotFoundPage(); return null; }
            var terms = BllInstance.TermManager.Select(t => true).ToList();
            var relations = BllInstance.RelationManager.Select(r => r.ObjectType == (short)RelationObjectType.Post).ToList();
            int totalCount;
            var posts = BllInstance.PostManager.SelectPage(page, Setting.PageSize, out totalCount, p => p.Status == (int)PostStatus.Default && p.Type == (int)PostType.Article && p.UserId == author.Id, p => p.PubDate, true);
            foreach (var post in posts)
            {
                var rIds = relations.Where(r => r.ObjectId == post.Id).Select(r => r.TermId).ToArray();
                var itemTerms = terms.Where(t => rIds.Contains(t.Id)).ToList();
                post.Link = Url.Post(post.Slug);

                author.Link = Url.Author(author.Login);
                post.Author = author;
                post.Categorys = itemTerms.Where(c => c.Type == (short)TermType.PostCategory);
                post.Tags = itemTerms.Where(c => c.Type == (short)TermType.PostTag);
            }
            ViewBag.Posts = posts;
            ViewBag.ListItem = new MvcHtmlString(string.Format("<a href=\"{0}\">{1}</a>的文字", Url.Action("Author", "Blog", new { item = author.Login }), author.NickName));
            ViewBag.ListDescription = author.Description;
            ViewBag.CurrentPage = page;
            ViewBag.TotalCount = totalCount;
            ViewBag.Title = string.Format("{0}的文章 - 第{1}页 | {2} - Powered by {3}", author.NickName, page, Setting.SiteName, Setting.Generator);
            return View(TemplateConfig.ListViewName);
        }
        #endregion

        #region 搜索列表页 +ViewResult Search(string q, int page = 1)
        /// <summary>
        /// 搜索列表页
        /// </summary>
        /// <param name="q">搜索关键词</param>
        /// <param name="page">页码</param>
        /// <returns></returns>
        public ViewResult Search(string q, int page = 1)
        {
            var terms = BllInstance.TermManager.Select(t => true).ToList();
            var relations = BllInstance.RelationManager.Select(r => r.ObjectType == (short)RelationObjectType.Post).ToList();

            int totalCount;
            var posts = BllInstance.PostManager.SelectPage(page, Setting.PageSize, out totalCount, p => p.Status == (int)PostStatus.Default && p.Type == (int)PostType.Article && (p.Title.Contains(q)), p => p.PubDate, true);
            var users = BllInstance.UserManager.Select(u => true).ToList();
            foreach (var post in posts)
            {
                var rIds = relations.Where(r => r.ObjectId == post.Id).Select(r => r.TermId).ToArray();
                var itemTerms = terms.Where(t => rIds.Contains(t.Id)).ToList();
                post.Link = Url.Post(post.Slug);
                var user = users.FirstOrDefault(u => u.Id == post.UserId);
                if (user != null)
                {
                    user.Link = Url.Author(user.Login);
                    post.Author = user;
                }
                post.Categorys = itemTerms.Where(c => c.Type == (short)TermType.PostCategory);
                post.Tags = itemTerms.Where(c => c.Type == (short)TermType.PostTag);
            }
            ViewBag.Posts = posts;
            ViewBag.ListItem = new MvcHtmlString(string.Format("搜索“<a href=\"{0}\">{1}</a>”出来的内容", Url.Action("Search", "Blog", new { q }), q));
            ViewBag.ListDescription = "各种" + q;
            ViewBag.CurrentPage = page;
            ViewBag.TotalCount = totalCount;

            ViewBag.Title = string.Format("“{0}”搜索出来的文章 - 第{1}页 | {2} - Powered by {3}", q, page, Setting.SiteName, Setting.Generator);
            return View(TemplateConfig.ListViewName);
        }
        #endregion

        #region Post详细页 +ViewResult Detail(string item)
        /// <summary>
        /// Post详细页
        /// </summary>
        /// <param name="item">文章项</param>
        /// <returns></returns>
        public ViewResult Detail(string item)
        {
            Post post;
            if (item.IsInt())
            {
                int id = item.ToInt(0);
                if (id == 0) { ShowNotFoundPage(); return null; }
                post = BllInstance.PostManager.SelectSingle(p => p.Id == id && p.Type == (short)PostType.Article);
            }
            else
                post = BllInstance.PostManager.SelectSingle(p => p.Slug == item && p.Type == (short)PostType.Article);
            if (post == null) { ShowNotFoundPage(); return null; }
            var rIds = BllInstance.RelationManager.Select(r => r.ObjectType == (short)RelationObjectType.Post && r.ObjectId == post.Id).Select(r => r.TermId).ToArray();
            var terms = BllInstance.TermManager.Select(t => rIds.Contains(t.Id)).ToList();
            post.Categorys = terms.Where(c => c.Type == (short)TermType.PostCategory);//string.Join("、", .Select(c => string.Format("<a href=\"{0}\" target=\"_blank\"> <i class=\"icon-list-alt icon12\"></i>{1}</a>", Url.Action("Category", "Blog", new { item = !string.IsNullOrEmpty(c.Slug) ? c.Slug : c.Name }), c.Name)));
            post.Tags = terms.Where(c => c.Type == (short)TermType.PostTag);// string.Join("、", .Select(c => string.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", Url.Action("Tag", "Blog", new { item = !string.IsNullOrEmpty(c.Slug) ? c.Slug : c.Name }), c.Name)));

            var user = BllInstance.UserManager.SelectSingle(u => u.Id == post.UserId);
            if (user != null)
            {
                user.Link = Url.Author(user.Login);
                post.Author = user;
            }
            else
            {
                user = new User { NickName = "匿名", Login = "guest", Link = Url.Author("guest") };
            }
            //var posts=BllInstance.PostManager.Select()

            post.Author = user;
            post.Link = Url.Post(post.Slug);
            post.Comments = BllInstance.CommentManager.Select(c => c.PostId == post.Id && c.Status == (short)CommentStatus.Approved).OrderByDescending(c => c.PubDate).ToList();
            post.Around = BllInstance.PostManager.GetPostAround(post);
            ViewBag.Post = post;
            ViewBag.User = user;

            ViewBag.Title = string.Format("{0} | {1} - Powered by Wedn.Net", post.Title, Setting.SiteName);
            return View(TemplateConfig.DetailViewName);
        }
        #endregion

        #region 页面详细页 +ViewResult Page(string item)
        /// <summary>
        /// 页面详细页
        /// </summary>
        /// <param name="item">页面项</param>
        /// <returns></returns>
        public ActionResult Page(string item)
        {
            Post post;
            if (item.IsInt())
            {
                int id = item.ToInt(0);
                if (id == 0) { return HttpNotFound(); }
                post = BllInstance.PostManager.SelectSingle(p => p.Id == id && p.Type == (short)PostType.Page);
            }
            else
                post = BllInstance.PostManager.SelectSingle(p => p.Slug == item && p.Type == (short)PostType.Page);
            if (post == null) { return HttpNotFound(); }
            var metaList = BllInstance.PostMetaManager.Select(m => m.PostId == post.Id);
            post.Meta = new Dictionary<string, string>();
            foreach (var postMeta in metaList)
            {
                post.Meta.Add(postMeta.Key, postMeta.Value);
            }
            ViewBag.Post = post;

            ViewBag.Title = string.Format("{0} | {1} - Powered by Wedn.Net", post.Title, Setting.SiteName);
            return View(TemplateConfig.PageViewName);
        }
        #endregion

    }
}
